<?php

namespace App\Http\Controllers\Ad;

use App\Events\Order;
use App\Http\Controllers\BaseController;
use App\Models\Ad;
use App\Models\AdPrice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Yansongda\Pay\Pay;

class AdController extends BaseController
{
    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'ad_hierarchy_id' => 'integer',
            'ad_category_id' => 'integer',
            'type' => 'in:1,2',
            'time' => 'in:asc,desc',
            'amount' => 'in:asc,desc',
            'user_id' => 'integer'
        ]);

        $query = Ad::query();


        if (isset($param['ad_hierarchy_id'])){
            $query->where('ad_hierarchy_id',$param['ad_hierarchy_id']);
        }

        if (isset($param['ad_category_id'])){
            $query->where('ad_category_id',$param['ad_category_id']);
        }

        if (isset($param['type'])){
            $query->where('type',$param['type']);
        }

        if (isset($param['area'])){
            $query->where('area',$param['area']);
        }

        if (isset($param['user_id'])){
            $query->where('user_id',$param['user_id']);
        }


        if (isset($param['time'])){
            $query->orderBy('created_at',$param['time']);
        }

        if (isset($param['amount'])){
            $query->orderBy('amount',$param['amount']);
        }

        $data = $query->where('audit_status',2)
                    ->orderByDesc('id')
                    ->get();

        return $this->success($data);
    }

    public function list(Request $request)
    {
        $param = $this->validate($request,[
            'status' => 'in:1,2,3,4,5'
        ]);

        $user_id = auth('api')->id();

        $query = Ad::query();
        if (isset($param['status'])){
            $query->where('status',$param['status']);
        }

        $orders =  $query->where('user_id',$user_id)->orderByDesc('id')->simplePaginate();

        return $this->success($orders);
    }

    public function put(Request $request)
    {
        $param = $this->validate($request,[
            'ad_hierarchy_id' => 'integer',
            'ad_category_id' => 'integer',
            'article_id' => 'integer'
        ]);

        $ads = Ad::query()->where($param)
                 ->with('user:id,nickname,avatar')
                 ->where(['audit_status' => 2,'status'=>3])
                 ->where('end_time','>',date('Y-m-d H:i:s'))
                 ->limit(8)->get();

        return $this->success($ads);

    }

    // 广告接单
    public function order(Request $request)
    {
        $param = $this->validate($request,[
            'ad_id' => 'required|integer',
            'article_id' => 'required|integer'
        ]);

        $ad = Ad::query()->where('id',$param['ad_id'])->first();

        if (empty($ad)){
            return $this->error('广告不存在');
        }

        if ($ad->status!=2){
            return $this->error('该广告已被接单');
        }

        $ad_share_profit = admin_setting_array('ad_share_profit');
        $rate = array_sum(array_values($ad_share_profit));

        $order_user_amount = bcmul((string)$ad->amount,bcdiv((string)(100-$rate),'100',2),2);

        $result = Ad::query()->where('id',$param['ad_id'])->update([
            'article_id' => $param['article_id'],
            'order_user_id' => auth('api')->id(),
            'order_user_amount' => $order_user_amount,
            'status' => 3,
            'put_time' => date('Y-m-d H:i:s'),
            'end_time' => date('Y-m-d H:i:s',strtotime('+'.$ad->days.' days'))
        ]);

        return  $result ? $this->success() : $this->error();
    }

    public function show(Request $request)
    {
        $param = $this->validate($request,[
            'ad_id' => 'required'
        ]);

        $data = Ad::query()
            ->with(['category:id,name','hierarchy:id,name'])
            ->where('id',$param['ad_id'])
            ->first();

        return $this->success($data);
    }


    public function store(Request $request)
    {
        $param =  $this->validate($request,[
            'ad_category_id' => 'required',
            'name' => 'required|max:100',
            'type' => 'required|in:1,2',
            'ad_hierarchy_id' => 'required',
            'area' => 'required',
            'days' => 'required',
            'instructions' => 'required|max:500',
            'material' => 'required',
            'pay_method' => 'required|in:1,2',
            'platform' => 'required|in:1,2,3'
        ]);

        $price =  AdPrice::query()
                        ->where([
                            'ad_category_id' => $param['ad_category_id'],
                            'ad_hierarchy_id' => $param['ad_hierarchy_id'],
                        ])->value('price');

        $user = auth('api')->user();
        $param['user_id'] = $user['id'];
        $param['trade_no'] = getTradeNo();
        $param['amount'] = bcmul($param['days'],$price,2);
        $param['parent_id'] = $user['parent_id'];
        $ad_share_profit = admin_setting_array('ad_share_profit');



        if ($user['parent_id']){
            $param['direct_distribution_income'] = bcmul((string)$param['amount'],(string)($ad_share_profit['direct_distribution_rate']/100),2);
            $param['grand_id'] = (int)DB::table('users')->where('id',$user['parent_id'])->value('parent_id');
            if ($param['grand_id']){
                $param['interposition_income'] =  bcmul((string)$param['amount'],(string)($ad_share_profit['direct_distribution_rate']/100),2);
            }

        }

        $ad = Ad::query()->create($param);
        if ($ad->getKey()){
            $config = config('pay');
            switch ($param['pay_method']){
                case 1 :
                    $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/ad/notify';
                    Pay::config($config);
                    $order = [
                        'out_trade_no' => $ad->trade_no,
                        'description' => '广告支付',
                        'amount' => [
                            'total' => (int)bcmul($ad->amount,100),
                        ],
                    ];
                    $payInfo = '';
                    switch ($param['platform']){
                        case 1:
                            $payInfo =  Pay::wechat()->app($order);
                            break;
                        case 2 :
                            $order['payer']['openid'] = $user['wx_min_openid'];
                            $payInfo = Pay::wechat()->mini($order);
                            break;
                        case 3 :
                            $result = Pay::wechat()->scan($order);
                            $payInfo = ['code_url' => $result->code_url,'trade_no'=> $ad->trade_no];
                            break;
                    }

                    return $this->success($payInfo);
                case 2 :

                    $config['alipay']['default']['notify_url'] = 'https://www.huashimu.com/api/ad/ali/notify';
                    $config['alipay']['default']['return_url'] = 'http://www.xn--4pvs78ay6h.xn--fiqs8s/#/advertisement';
                    Pay::config($config);
                    if ($param['platform']==1){

                        $aliPay  = Pay::alipay()->app([
                            'out_trade_no' =>  $ad->trade_no,
                            'total_amount' => $ad->amount,
                            'subject' => '广告支付',
                        ])->getBody()->getContents();
                    }else{
                        $aliPay = Pay::alipay()->web([
                            'out_trade_no' => $ad->trade_no,
                            'total_amount' => $ad->amount,
                            'subject' => '广告支付',
                        ])->getBody()->getContents();
                    }

                    return  $this->success(['payInfo' => $aliPay]);
            }

;
        }

        return  $this->error();

    }


    public function str_to_utf8 ($str = '') {
        $current_encode = mb_detect_encoding($str, array("ASCII","GB2312","GBK",'BIG5','UTF-8'));
        $encoded_str = mb_convert_encoding($str, 'UTF-8', $current_encode);
        return $encoded_str;
    }

    public function notify()
    {
        $config = config('pay');
        $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/ad/notify';
        Pay::config($config);

        $result = Pay::wechat()->callback()->toArray();

        Storage::put('a2.txt',json_encode($result));

        if ($result && $result['event_type'] == 'TRANSACTION.SUCCESS'){
            $order = Ad::query()->where('trade_no',$result['resource']['ciphertext']['out_trade_no'])->first();

            if ($order && $order->status==1){
                $trade_time = date('Y-m-d H:i:s',strtotime($result['resource']['ciphertext']['success_time']));

                event(new Order($order->user_id));
                Ad::query()->where('id',$order->id)->update([
                    'status' => 2,
                    'pay_time' => $trade_time
                ]);

                event(new \App\Events\Message([
                    'user_id' =>  $order->user_id,
                    'type' => 3,
                    'content' => '你发布广告已付款成功,请耐心等待平台审核!'
                ]));

                return Pay::wechat()->success();
            }

        }
    }


    public function aliNotify()
    {
        $config = config('pay');
        Pay::config($config);

        $result = Pay::alipay()->callback()->toArray();
        if ($result['trade_status']=='TRADE_SUCCESS'){
            $order = Ad::query()->where('trade_no',$result['out_trade_no'])->first();
            if ($order && $order->status==1){
                event(new Order($order->user_id));
                Ad::query()->where('id',$order->id)->update([
                    'status' => 2,
                    'pay_time' =>$result['gmt_payment']
                ]);

                event(new \App\Events\Message([
                    'user_id' =>  $order->user_id,
                    'type' => 3,
                    'content' => '你发布广告已付款成功,请耐心等待平台审核!'
                ]));

                return Pay::alipay()->success();
            }

        }

    }
}
